package com.yuven.appframework.network

import com.google.gson.GsonBuilder
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.logging.HttpLoggingInterceptor
import java.security.cert.X509Certificate
import java.util.*
import javax.net.ssl.X509TrustManager


object RequestHelper {

    var cookiesStore = HashMap<String, List<Cookie>>()


    val  x509TrustManager = object :X509TrustManager{
        override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
        }

        override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
        }

        override fun getAcceptedIssuers(): Array<X509Certificate?>? {
            return arrayOfNulls(0)
        }

    }
//    var sslSocketFactory: SSLSocketFactory? =
//        SSLSocketFactoryCompat(x509TrustManager)
//    private var mClient: OkHttpClient
//    init {
//
//        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
//            mClient = OkHttpClient.Builder()
//                .connectTimeout(30, TimeUnit.SECONDS)
//                .readTimeout(30, TimeUnit.SECONDS)
//                .addInterceptor(addXLogInterceptor())
//                .sslSocketFactory(sslSocketFactory, x509TrustManager)
//                .hostnameVerifier { hostname, session -> true }
//                .cookieJar(object : CookieJar {
//                    override fun saveFromResponse(httpUrl: HttpUrl, list: List<Cookie>) {
//                        cookiesStore[httpUrl.host()] = list
//                    }
//
//                    override fun loadForRequest(httpUrl: HttpUrl): List<Cookie> {
//                        val cookies: List<Cookie>? = cookiesStore[httpUrl.host()]
//                        return cookies ?: ArrayList()
//                    }
//                }).build()
//        }else{
//            mClient = OkHttpClient.Builder()
//                .connectTimeout(30, TimeUnit.SECONDS)
//                .readTimeout(30, TimeUnit.SECONDS)
//                .addInterceptor(addXLogInterceptor())
//                .cookieJar(object : CookieJar {
//                    override fun saveFromResponse(httpUrl: HttpUrl, list: List<Cookie>) {
//                        cookiesStore[httpUrl.host()] = list
//                    }
//
//                    override fun loadForRequest(httpUrl: HttpUrl): List<Cookie> {
//                        val cookies: List<Cookie>? = cookiesStore[httpUrl.host()]
//                        return cookies ?: ArrayList()
//                    }
//                }).build()
//        }
//
//    }


    fun doRequest(tag:Any,requestBuider: Request.Builder, cb:Callback){
//        var requestId = UUID.randomUUID().toString()
//        var token = ""
//        if(token == null)
//            token = ""
//        requestBuider.addHeader("x-Source", Build.MANUFACTURER)
//        requestBuider.addHeader("requestId",requestId)
//        requestBuider.addHeader("token",token)
//        requestBuider.addHeader("appId",APPID)
//        requestBuider.tag(tag)
//        var sign = Md5Util.stringToMD5(requestId+APPID+token+ SECRECT_KEY)
//        requestBuider.addHeader("sign",sign.lowercase())
//        mClient.newCall(requestBuider.build()).enqueue(cb)
    }


    @Deprecated("建议废弃doRequest,新doRequest透传tag标签通过VM管理请求生命周期",
        ReplaceWith("this.code.doRequest(tag:Any,requestBuider: Request.Builder, cb:Callback)"))
    fun doRequest(requestBuider: Request.Builder, cb:Callback){
//        var requestId = UUID.randomUUID().toString()
//        var token = ""
//        if(token == null)
//            token = ""
//        requestBuider.addHeader("x-Source", Build.MANUFACTURER)
//        requestBuider.addHeader("requestId",requestId)
//        requestBuider.addHeader("token",token)
//        requestBuider.addHeader("appId",APPID)
//        var sign = Md5Util.stringToMD5(requestId+APPID+token+ SECRECT_KEY)
//        requestBuider.addHeader("sign",sign.lowercase())
//        mClient.newCall(requestBuider.build()).enqueue(cb)
    }

    fun doOtherRequest(requestBuider: Request.Builder,cb:Callback){
//        mClient.newCall(requestBuider.build()).enqueue(cb)
    }

    private fun addXLogInterceptor():HttpLoggingInterceptor{
        val httpLoggingInterceptor = HttpLoggingInterceptor(OkHttpXLog())
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY  //log打印级别，决定了log显示的详细程度
        return httpLoggingInterceptor;
    }

//    public fun doDataReport(data:ReportDataBody){
//        val databodyJson = JsonFormatter(data)
//        var url = GlobalConfig.BASE_URL+"/bilog/upload"
//        val body = createRequestBody(databodyJson)
//        val requestBuilder = Request.Builder()
//        requestBuilder.url(url)
//        requestBuilder.post(body)
//        doRequest(requestBuilder,object :Callback{
//            override fun onFailure(call: Call, e: IOException) {
//                Logger.e(TAG,"doDataReport onFailure:${e.toString()}")
//            }
//
//            override fun onResponse(call: Call, response: Response) {
//                var rspStr = response.body()?.string()
//                Logger.i(TAG,"doDataReport rspStr:$rspStr")
//            }
//        })
//    }
//
//    public fun doDataReport(action:String){
//        var reprotDataBody = ReportDataBody(action, APPID)
//        doDataReport(reprotDataBody)
//    }



    /**
     * 格式化json
     * @param object
     * @return
     */
    fun jsonFormatter(json: Any?): String {
        if (json == null) {
            return ""
        }
        val gson = GsonBuilder().setPrettyPrinting().create()
        return gson.toJson(json)
    }

    fun createRequestBody(json: String?): RequestBody? {
        return json?.let {
            RequestBody.create(
                "application/json; charset=utf-8".toMediaTypeOrNull(),
                it
            )
        }
    }

    /**
     * 取消tag
     * @param tag tag
     */
    fun cancel(tag: Any) {
//        val dispatcher: Dispatcher = mClient.dispatcher
//        for (call in dispatcher.queuedCalls()) {
//            if (tag == call.request().tag()) {
//                call.cancel()
//            }
//        }
//        for (call in dispatcher.runningCalls()) {
//            if (tag == call.request().tag()) {
//                call.cancel()
//            }
//        }
    }

}